var map = null;
var divMap = null;
var polylines = new Array();
var polylineEdit = null;
//var polylineOptions = null;
var arrPointsfitbound = new Array();
var polygonOptions = null;
var allmarkers = new Array();
var polygon = null;

//bien tuong tac hanh chinh
var administratorService = null;

//bien ve ranh gioi hanh chinh cua Phuong Xa
var objCommunePolygon = null;

var areaServiceUrl = null;

//var strDiaBan = $('#selectDiBanDieuTra').val();
var option = null

var strCommuneCode = null;


// Ham khoi tao map va mot so doi tuong
function loadMapToDraw(index, serviceUrl, strCommuneCodePara) {
    // Khoi tao map
    divMap = document.getElementById('map');

    strCommuneCode = strCommuneCodePara;

    var mapTypeID = viettel.MapTypeId.TRAFFIC;
    var mapZoom = 16; //muc zoom mac dinh
    var panZoomControlPosition = 4;
    var centerPoint = new viettel.LatLng(21.0252531, 105.773691);

    map = new viettel.Map(divMap, {
        zoom: mapZoom,
        mapTypeId: mapTypeID,
        searchControl: false,
        panZoomControl: true,
        panZoomControlOptions: { position: panZoomControlPosition }, //thay doi vi tri cua panZoomControl
        scrollwheel: true,
    });
    
    areaServiceUrl = serviceUrl;

    administratorService = new viettel.AdministrationService();
    administratorService.setReturnType(viettel.AdminReturnType.CODE | viettel.AdminReturnType.NAME
        | viettel.AdminReturnType.PATH | viettel.AdminReturnType.BOUND); //Them return BOUND de phuc vu highlight KVHC

    //gopro, 20150115: hien thi ranh gioi Phuong Lang Thuong de Demo
    selectCommune();

    $('#selectDiBanDieuTra').change(function () {
        $('#btnnew').hide(1000);
        $('#btnconfirm').hide(1000);
        $('#btncontinue').hide(1000);
        deletearrPointsfitbound();
        var strMaDiaBan = "";
        strMaDiaBan = $('#selectDiBanDieuTra').val();

        if (strMaDiaBan == "") {
            deleteMarkers();
            selectCommune();
            return;
        }
        getBoundPoints(strMaDiaBan);
        polylineEdit.setMap(null);
        //map.fitBounds(getBoundary(arrPointsfitbound));
        return;
    });

    $('#no').click(function () {
        $('#btncontinue').show(1000);
        $('#optionDiaBanDieuTra').show(1000);
        $('#btnconfirm').hide(1000);
        return;
    });

    $('#drawnew').click(function () {
        $('#btnconfirm').hide(1000);
        $('#btnnew').hide(1000);
        $('#btncontinue').hide(1000);
        endDrawPolyline();
    });

    $('#yes').click(function () {
        $('#divLoading').show();
        $('#optionDiaBanDieuTra').show(1000);
        $('#btnconfirm').hide(1000);
        var arrPointData = new Array();
        //dua ma dia ban dieu tra dang ve vao
        arrPointData.push($('#selectDiBanDieuTra').val());
        //toa do ranh gioi dia ban dieu tra
        for (var i = 0; i < arrPointsfitbound.length; i++) {
            arrPointData.push(arrPointsfitbound[i].toString());
        }
        var postData = { values: arrPointData };
        $.ajax({
            type: "POST",
            headers: headers,
            url: strUrlAddBP,
            data: postData,
            success: function (data) {
                $('#divLoading').hide();
                $('#success').show(1000);
            },
            dataType: "json",
            traditional: true
        });
    });

    $('#continue').click(function () {
        $('#btncontinue').hide(1000);
        deletearrPointsfitbound();
        deleteMarkers();
        selectCommune();
        initDrawPolyline();
        endDrawPolyline();
    });

    $('#viewArea').click(function () {
        deleteMarkers();
        deletearrPointsfitbound();
        $('#btnnew').hide(1000);
        $('#btnconfirm').hide(1000);
        $('#btncontinue').hide(1000);
        initDrawPolyline();
        selectCommune();
        polylineEdit.setMap(null);
        //map.fitBounds(getBoundary(arrPointsfitbound));
        return;
    });

    $(".control-close").click(function (e) {
        var parent = $(this).parent().parent();
        if (parent.children(".middle").css("display") == "none") {
            $(this).css("background-position", "");
            parent.children(".middle").css("display", "block");
            if (parent.attr("id") == "view-level-control") { $("#heat-scale").css("top", "400px") }
        } else {
            $(this).css("background-position", "-18px 0px");
            parent.children(".middle").css("display", "none");
            if (parent.attr("id") == "view-level-control") { $("#heat-scale").css("top", "320px") }
        }
    });

}

//hiển thị thành phố hiện tại
function selectCommune() {
    var code = strCommuneCode;
    administratorService.setLevel(viettel.AdminLevelType.COMMUNE);
    administratorService.getFeatureFromCode(code, function (status, result) {
        drawCommune(status, result);
    });
}

//ve Phuong Lang Thuong - Dong Da - Ha Noi
function drawCommune(status, result) {
    if (status == 0) {
        var item = result.items[0];
        objCommunePolygon = new viettel.Polygon({
            paths: item.paths,
            strokeColor: "#E7746F",
            strokeOpacity: 0.9,
            strokeWeight: 0.9,
            fillColor: "#FF0000",
            fillOpacity: 0.02,
            clickable: false,
            map: map
        });
        allmarkers.push(objCommunePolygon);
        map.fitBounds(item.bound);
    }
}

//hiển thị tất cả các nơi đã vẽ
function initDrawPolyline() {
    $.ajax({
        url: strUrlGetAllCode,
        headers: headers,
        type: "GET",
        dataType: "json",
        cache: false,
        success: function (data) {
            jsonResult = data;
        },
        error: function (xhr) {
            alert('Không nối được đến database 189!');
            return null;
        },
        complete: function (jqXHR, textStatus) {
            if (jsonResult.length != 0) {
                $.each(jsonResult, function (i, item) {
                    $("#divLoading").show();
                    $.ajax({
                        url: strUrlGetAreaCode,
                        headers: headers,
                        type: "GET",
                        dataType: "json",
                        cache: false,
                        data: { 'AREA_CODE': item },
                        success: function (data) {
                            jsonResult = data;
                        },
                        error: function (xhr) {
                            alert('Không kết được đến Database 209!');
                            return null;
                        },
                        complete: function (jqXHR, textStatus) {
                            $("#divLoading").hide();
                            if (jsonResult.length != 0) {
                                var arrPoints = new Array();
                                $.each(jsonResult, function (i, item) {
                                    arrPoints.push(new viettel.LatLng(item.Lat, item.Lon));
                                });
                                 polygon = new viettel.Polygon({
                                    paths: arrPoints,
                                    strokeColor: "#006400",
                                    strokeOpacity: 0.8,
                                    strokeWeight: 0.9,
                                    fillColor: "#006400",
                                    fillOpacity: 0.1,
                                    clickable: true,
                                    map: map
                                });
                                 allmarkers.push(polygon);
                            }
                        }
                    });
                });
            }
            
        }
    });
    return;
}

//ve địa bàn mới
function endDrawPolyline() {
    var polylineOptions = {
        strokeColor: "#0000FF",
        strokeOpacity: 0.4,
        strokeWeight: 6,
        clickable: true,
        map: map
    };
    polylineEdit = new viettel.Polyline(polylineOptions);
    polylineEdit.setDrawing(true);
    
    viettel.Events.addListenerOnce(polylineEdit, "endDraw", function () {
        arrPointsfitbound = polylineEdit.getPath().getArray();
        polygon = new viettel.Polygon({
            paths: arrPointsfitbound,
            strokeColor: "#8B008B",
            strokeOpacity: 0.8,
            strokeWeight: 0.9,
            fillColor: "#8B008B",
            fillOpacity: 0.1,
            clickable: true,
            map: map
        });

        allmarkers.push(polygon);
        // Xoa doi tuong edit khoi ban do
        polylineEdit.setMap(null);
        map.fitBounds(getBoundary(arrPointsfitbound));
        $('#btnconfirm').show(1000);
        return;
    })
    
    return;
}

// Tra ve boundary tu path
function getBoundary(path) {
    var b = new viettel.LatLngBounds();
    for (var i = 0; i < path.length; i++) {
        b = b.extend(path[i]);
    }
    return b;
}


//kiểm tra địa bàn đã vẽ chưa.
//vẽ rồi k cho vẽ nữa. Chưa vẽ sẽ cho vẽ
function getBoundPoints(strMaDiaBan) {
    var jsonResult;
    $.ajax({
        url: strUrlGetAreaCode,
        headers: headers,
        type: "GET",
        dataType: "json",
        cache: false,
        data: { 'AREA_CODE': strMaDiaBan },
        success: function (data) {
            jsonResult = data;
        },
        error: function (xhr) {
            alert('Không kết nối được đến database 300!');
            return null;
        },
        complete: function (jqXHR, textStatus) {
            deleteMarkers();
            selectCommune();
            if (jsonResult.length != 0) {
                var arrPoints = new Array();
                $.each(jsonResult, function (i, item) {
                    arrPoints.push(new viettel.LatLng(item.Lat, item.Lon));
                });
                 polygon = new viettel.Polygon({
                    paths: arrPoints,
                    strokeColor: "#938FF4",
                    strokeOpacity: 0.8,
                    strokeWeight: 0.9,
                    fillColor: "#938FF4",
                    fillOpacity: 0.1,
                    clickable: true,
                    map: map
                });

                allmarkers.push(polygon);
                //map.fitBounds(getBoundary(arrPoints));
                $('#btnconfirm').hide(1000);
                $('#btnnew').hide(1000);
                $('#btncontinue').hide(1000);
                return;
            }
            else
            {
                initDrawPolyline();
                $('#btnnew').show(1000);
                //return;
            }
        }
    });
}

function deleteMarkers() {
    if (allmarkers != null) {
        for (var i = 0; i < allmarkers.length; i++) {
            allmarkers[i].setMap(null);
        }
    }
    allmarkers = new Array();
}

function deletearrPointsfitbound() {
    if (arrPointsfitbound != null) {
            arrPointsfitbound.splice(0, arrPointsfitbound.length);
    }
}
